local Buff 	  = require("app.battleV3.ui.objs.Buff")

local BuffView = MClass("BuffView")
local BUFF_ZENGYI = 1 --蓝色
local BUFF_JIANYI = 2 --红色

function BuffView:ctor()
	--self.root 默认为根节点
	self._buffkeys = {}
	local key
	for i = 1, BattleUIConst.BuffMax do
		key = string.format("buff_%d", i)
		table.insert(self._buffkeys, key)
		self[key] = Buff.new(self:findChild(key))
	end
    self:init()
end

function BuffView:init()
	local size = self:getContentSize()
    self._height = size.height
	self:reset()
	BattleUIEvent:addEventListener(BattleUIEvent.TYPE.BUFF_SELT, handler(self,BuffView.setData))
end

function BuffView:reset()
	local keys = self._buffkeys
	for i = 1, BattleUIConst.BuffMax do
		self[keys[i]].root:setVisible(false)
	end
end

function BuffView:setData(data,id)
	self:reset()
	if not data then return end
	local buffs = self:reSortBuffs(data)
	local keys = self._buffkeys
	for i = 1, #buffs do
		if i > BattleUIConst.BuffMax then
			--todo
			break
		end
		self[keys[i]]:setTargetId(id)
		self[keys[i]]:setData(buffs[i])
	end
end

function BuffView:getHeight()
	return self.height or 0
end

function BuffView:reSortBuffs(buffs)
	--table.insert(self.buffIconDict, {bShowCD = buffCfg.bShowCD, buffId = buffCfg.buffId, name = buffCfg.name, icon = iconPath, desc = buffCfg.desc, displaySort = buffCfg.displaySort, layerCount = layerCount, leftTime = leftTime,createTime = createTime})

	--displaysort 5 3
	--create time
	local z_buffs = {}
	local j_buffs = {}
	local result  = {}

	for _, buff in pairs(buffs or {}) do
		if buff.displaySort == BUFF_ZENGYI then
			table.insert(z_buffs,buff)
		end
		if buff.displaySort == BUFF_JIANYI then
			table.insert(j_buffs,buff)
		end
	end

	table.sort(z_buffs,function(l,r) 
        return l.createTime < r.createTime
    end)

    table.sort(j_buffs,function(l,r) 
        return l.createTime < r.createTime
    end)

    local j_start = #j_buffs > 5 and #j_buffs-5 or 1
    for j_start,buff in ipairs(j_buffs) do
    	table.insert(result,buff)
    end

    local z_start = #z_buffs > 3 and #z_buffs-3 or 1
    for z_start,buff in ipairs(z_buffs) do
    	table.insert(result,buff)
    end

    return result
end


return BuffView